package org.cadet.client.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.cadet.client.bean.BeanThought;
import org.cadet.client.bean.BeanUser;
import org.cadet.client.model.ThoughtManagement;
import org.cadet.client.model.UserManagement;

/**
 * @author Nagmani
 *
 */

public class DashboardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DashboardServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		try {
			HttpSession session = request.getSession();
			ArrayList<BeanThought> thoughts = null;
			ThoughtManagement objThoughtManagement = new ThoughtManagement();
			ArrayList<BeanUser> authors = null;
			UserManagement objUserManagement = new UserManagement();
			int currentUserId = objUserManagement.getUserIdByName((String)session.getAttribute("user"));
			String status = "", authorId="";
			try{
				try{
					authorId = request.getParameter("hdnAuthorId").toString();
					session.setAttribute("userId", authorId);
					session.setAttribute("userName", objUserManagement.viewUserByUserId(Integer.parseInt(authorId)));
				}
				catch(Exception e){
					session.setAttribute("userId","0");
				}
				if(authorId.compareTo("0") == 0){
					thoughts = objThoughtManagement.viewFollowedUserThought(currentUserId);
				}
				else
					thoughts = objThoughtManagement.viewAuthorwiseThought(Integer.parseInt(authorId));
			    authors = objUserManagement.viewFollowedUsers(currentUserId);
				status = "success";
			}
			catch(Exception e){
				status = "fail";
			}
			
			request.setAttribute("status", status);
			request.setAttribute("thoughts", thoughts);
			request.setAttribute("authors", authors);
			request.setAttribute("authorId", authorId);

			RequestDispatcher rd = request.getRequestDispatcher("/client/index.jsp");
			rd.forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
